<?php

namespace app\admin\model;

use app\common\model\TimeModel;
use think\facade\Db;
use think\facade\Log;

class ShopFinanceDay extends TimeModel
{

    protected $name = "shop_finance_day";

    protected $deleteTime = false;


    /**
     * @title 更新店铺收入日统计
     * @author FashionJune
     * @param array $data
     */
    public function updateFinance(array $data)
    {
        $row = $this->where('date', $data['date'])->find();
        Db::startTrans();
        try {
            if ($row) {//更新
                $save_data = [
                    'price_total' => Db::raw('price_total + ' . $data['price_total']),
                    'cashcard_total' => Db::raw('cashcard_total + ' . $data['cashcard_total']),
                ];
                $row->save($save_data);
            } else {//新建
                $save_data = [
                    'date' => $data['date'],
                    'store_id' => $data['store_id'],
                    'price_total' => $data['price_total'],
                    'cashcard_total' => $data['cashcard_total'],
                ];
                $this->save($save_data);
            }
            //更新系统统计
            $values = [$data['price_total'], $data['cashcard_total']];
            $keys = ['user_consume', 'cashcard_use'];
            SystemFinanceDay::init()->updateFinance($values, $keys);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error('更新统计失败');
        }
    }
    

}